﻿using System.Collections.Generic;
using EnetaMvc.Core.Domain.Content;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;
using NHibernate;
using NHibernate.Criterion;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class ContentItemRepository : BaseRepository, IContentItemRepository
    {
        private readonly ISession _session;

        public ContentItemRepository(IMapperSession session) : base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
        }

        public ContentItem GetContentItemById(long id)
        {
            return _session.Get<ContentItem>(id);
        }


        public PagedResult<T> ListContentItems<T>(int page, int pageSize) where T : ContentItem
        {
            var criteria = _session.CreateCriteria<T>();
            criteria.CreateCriteria("PublishState")
                    .Add(Expression.Eq("IsVisibleOnPublicSite", true));

            return GetPagedResultForQuery<T>(criteria, page, pageSize);
        }

        public IList<T> ListPendingContentItems<T>(int rowLimit) where T : ContentItem
        {
            var criteria = _session.CreateCriteria<T>();
            criteria.CreateCriteria("PublishState").Add(Expression.Eq("Id", 2L));
            criteria.AddOrder(Order.Desc("Created"));

            if (rowLimit > 0)
                criteria.SetMaxResults(rowLimit);

            return criteria.List<T>();
        }


        public IList<T> ListContentItemsByTagId<T>(long tagId) where T : ContentItem
        {
            var criteria = _session.CreateCriteria<ContentItem>()
                            .CreateCriteria("Tags").Add(Expression.Eq("Id", tagId));
            return criteria.List<T>();
        }


        public void DeleteContentItemsByTagId(long tagId)
        {
            var contentItemsByTagId = ListContentItemsByTagId<ContentItem>(tagId);
            foreach (var item in contentItemsByTagId)
                DeleteInTransaction(item);
        }
    }
}
